package middleware

import (
	"context"
	"github.com/gin-gonic/gin"
	"github.com/vueadmin/global"
	"github.com/vueadmin/utils"
	"github.com/vueadmin/utils/common/request"
	"github.com/vueadmin/utils/conv"
	e "github.com/vueadmin/utils/exception"
)

// 验证短信中间件
func SmsAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		var req request.SmsReq
		if err := utils.BindAndValid(c, &req); err != nil {
			panic(e.ValidateError(err.Error()))
		}
		data, _ := global.REDIS.Get(context.Background(), req.VerifyId).Result()
		if data == "" {
			panic(e.ValidateError("验证码已过期或不存在"))
		}

		res := conv.StringToObject(data)
		if conv.String(res["mobile"]) != req.Mobile {
			panic(e.ValidateError("手机号与验证不一致"))
		}

		if res["verify"] != req.Verify {
			panic(e.ValidateError("验证码错误"))
		}

		//global.REDIS.Del(context.Background(), req.VerifyId)

		c.Next()
	}
}
